package delayqueue

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"net/http"
)

type stats struct {
	Jobs     interface{} `json:"jobs"`
	Enqueued interface{} `json:"enqueued"`
}

func Stats(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	jobs := make(map[string][]*map[string]interface{})
	enqueued := make(map[string]string)

	for queue, manager := range managers {
		tasksLen, _ := manager.lenTasks()
		keys, _ := manager.allTasks()
		jobs[queue] = append(jobs[queue], &map[string]interface{}{
			"concurrency": manager.concurrency,
			"len":         tasksLen,
			"keys":        keys,
		})
	}

	stats := stats{
		jobs,
		enqueued,
	}

	body, _ := json.MarshalIndent(stats, "", "  ")
	fmt.Fprintln(w, string(body))
}

func StatsServer(port int) {
	http.HandleFunc("/stats", Stats)

	logrus.Println("Stats are available at", fmt.Sprint("http://localhost:", port, "/stats"))

	if err := http.ListenAndServe(fmt.Sprint(":", port), nil); err != nil {
		logrus.Println(err)
	}
}
